import { defineStore } from 'pinia'
import { Register, Login, Logout } from '@/api/account'
export const useAppStore = defineStore('app', {
    state: () => ({
        token: '',
        username: '',
        collapse: false
    }),
    getters: {},
    actions: {
        registerAction(requestData) {
            return new Promise((resolve, reject) => {
                Register(requestData)
                    .then((response) => {
                        resolve(response)
                    })
                    .catch((error) => {
                        reject(error)
                    })
            })
        },
        loginAction(requestData) {
            return new Promise((resolve, reject) => {
                Login(requestData)
                    .then((response) => {
                        resolve(response)
                    })
                    .catch((error) => {
                        reject(error)
                    })
            })
        },
        toggleCollapseAction() {
            this.collapse = !this.collapse
        },
        updateToken(token) {
            this.token = token
        },
        updateUsername(username) {
            this.username = username
        },
        loginAction(requestData) {
            return new Promise((resolve, reject) => {
                Login(requestData)
                    .then((response) => {
                        const { token, username } = response.data
                        this.updateToken(token)
                        this.updateUsername(username)
                        resolve(response)
                    })
                    .catch((error) => {
                        reject(error)
                    })
            })
        },
        logoutAction() {
            return new Promise((resolve, reject) => {
                Logout()
                    .then((response) => {
                        this.updateToken('')
                        this.updateUsername('')
                        resolve(response)
                    })
                    .catch((error) => {
                        reject(error)
                    })
            })
        },
    },
    persist: {
        storage: sessionStorage,
        key: 'pinia.app'
    }
})